<template>
  <div class="one-box">
    <div class="TwinSafety-title-left">
      <div class="BoxTitle-title-fangkuai"></div>
      <div class="BoxTitle-title-title">设备告警</div>
    </div>
    <div class="danwei">单位 : 个</div>
    <div id="customerChartD1"></div>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue"
import { getCurrentInstance } from "vue" //访问内部组件实例
const { appContext } = getCurrentInstance()
const { $echarts, fontSize } = appContext.config.globalProperties
onMounted(() => {
  nextTick(() => {
    initEcharts()
  })
})

const shujvList = ref([
  {
    name: "1号储能单元",
    value: 100
  },
  {
    name: "2号储能单元",
    value: 100
  },
  {
    name: "3号储能单元",
    value: 57
  },
  {
    name: "4号储能单元",
    value: 51
  },
  {
    name: "5号储能单元",
    value: 11
  }
])
let yanse = ["#e5c647", "#8cddf0", "#56f6a4"]
shujvList.value.forEach((item, index) => {
  item.itemStyle = {
    color: yanse[index]
  }
})
const initEcharts = () => {
  let myChart = $echarts.getInstanceByDom(
    document.getElementById("customerChartD1")
  )
  if (myChart) {
    myChart.dispose()
  }
  // 如果不存在，就进行初始化
  myChart = $echarts.init(document.getElementById("customerChartD1"))

  // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
  function getParametricEquation(
    startRatio,
    endRatio,
    isSelected,
    isHovered,
    k,
    h
  ) {
    // 计算
    let midRatio = (startRatio + endRatio) / 2

    let startRadian = startRatio * Math.PI * 2
    let endRadian = endRatio * Math.PI * 2
    let midRadian = midRatio * Math.PI * 2

    // 如果只有一个扇形，则不实现选中效果。
    // if (startRatio === 0 && endRatio === 1) {
    //     isSelected = false;
    // }
    isSelected = false
    // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
    k = typeof k !== "undefined" ? k : 1 / 3

    // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
    let offsetX = isSelected ? Math.sin(midRadian) * 0.1 : 0
    let offsetY = isSelected ? Math.cos(midRadian) * 0.1 : 0

    // 计算高亮效果的放大比例（未高亮，则比例为 1）
    let hoverRate = isHovered ? 1.05 : 1

    // 返回曲面参数方程
    return {
      u: {
        min: -Math.PI,
        max: Math.PI * 3,
        step: Math.PI / 32
      },

      v: {
        min: 0,
        max: Math.PI * 2,
        step: Math.PI / 20
      },

      x: function (u, v) {
        if (u < startRadian) {
          return (
            offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        if (u > endRadian) {
          return (
            offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate
      },

      y: function (u, v) {
        if (u < startRadian) {
          return (
            offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        if (u > endRadian) {
          return (
            offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate
      },

      z: function (u, v) {
        if (u < -Math.PI * 0.5) {
          return Math.sin(u)
        }
        if (u > Math.PI * 2.5) {
          return Math.sin(u) * h * 0.1
        }
        return Math.sin(v) > 0 ? 1 * h * 0.1 : -1
      }
    }
  }

  // 生成模拟 3D 饼图的配置项
  function getPie3D(pieData, internalDiameterRatio) {
    let series = []
    let sumValue = 0
    let startValue = 0
    let endValue = 0
    let legendData = []
    let k =
      typeof internalDiameterRatio !== "undefined"
        ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
        : 1 / 3

    for (let i = 0; i < pieData.length; i++) {
      sumValue += pieData[i].value

      let seriesItem = {
        name:
          typeof pieData[i].name === "undefined"
            ? `series${i}`
            : pieData[i].name,
        type: "surface",
        parametric: true,
        wireframe: {
          show: false
        },
        pieData: pieData[i],
        pieStatus: {
          selected: false,
          hovered: false,
          k: 1 / 10
        }
      }

      if (typeof pieData[i].itemStyle != "undefined") {
        let itemStyle = {}

        typeof pieData[i].itemStyle.color != "undefined"
          ? (itemStyle.color = pieData[i].itemStyle.color)
          : null
        typeof pieData[i].itemStyle.opacity != "undefined"
          ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
          : null

        seriesItem.itemStyle = itemStyle
      }
      series.push(seriesItem)
    }

    for (let i = 0; i < series.length; i++) {
      endValue = startValue + series[i].pieData.value

      series[i].pieData.startRatio = startValue / sumValue
      series[i].pieData.endRatio = endValue / sumValue
      series[i].parametricEquation = getParametricEquation(
        series[i].pieData.startRatio,
        series[i].pieData.endRatio,
        false,
        false,
        k,
        series[i].pieData.value
      )

      startValue = endValue

      legendData.push(series[i].name)
    }

    // 准备待返回的配置项，把准备好的 legendData、series 传入。
    let option = {
      xAxis3D: {},
      yAxis3D: {},
      zAxis3D: {},
      grid3D: {
        viewControl: {
          autoRotate: true, //自动旋转
          distance: 100, //初始的大小
          alpha: 20, //初始的角度
          beta: 15,
          rotateSensitivity: 5, //鼠标拖动灵敏度
          zoomSensitivity: 1, //鼠标滚轮放大灵敏度
          panSensitivity: 1 //鼠标滚轮缩小灵敏度
        },
        // left: "center",
        width: "150px",
        show: false,
        boxHeight: 15
      },
      legend: {
        orient: "vertical",
        right: "1%",
        top: "20%",
        itemGap: 4,
        itemWidth: 12,
        itemHeight: 12,
        selectedMode: false, // 关闭图例选择
        textStyle: {
          color: "#fff",
          fontSize: 10,
          fontFamily: "Source Han Sans CN",
          rich: {
            name: {
              color: "black",
              fontSize: 12,
              width: 70,
              padding: [0, 0, 0, 0]
            },
            value: {
              color: "balck",
              // fontFamily: "PangMenZhengDao",
              fontSize: 12,
              width: 50,
              padding: [0, 0, 0, 0]
            }
          }
        },
        formatter: (name) => {
          let obj = pieData.find((item) => item.name === name)
          let datas = pieData
          let total = 0
          let target = obj.value
          for (let i = 0; i < datas.length; i++) {
            total += Number(datas[i].value)
          }
          // const arr = [`{iconName|}{name|${name}}{value|${obj.value}}`]
          const arr = [`${name}`]
          return arr.join("")
        }
      },
      tooltip: {
        formatter: (params) => {
          if (params.seriesName !== "mouseoutSeries") {
            return `${
              params.seriesName
            }<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${
              params.color
            };"></span>${option.series[params.seriesIndex].pieData.value}`
          }
          return ""
        }
      },
      series: series
    }
    return option
  }

  // 传入数据生成 option
  let option = getPie3D(shujvList.value, 0.8)

  myChart.setOption(option)
}
</script>
<style scoped lang="less">
.one-box {
  width: 222px;
  height: 125px;
  #customerChartD1 {
    width: 100%;
    height: 100%;
  }
  .TwinSafety-title-left {
    position: absolute;
    top: 0px;
    left: 10px;
    width: 100px;
    height: 35px;
    display: flex;
    align-items: center;
    .BoxTitle-title-fangkuai {
      width: 10px;
      height: 10px;
      background: url("@/assets/TwinSafety/icon_xiaobiaoti.png") no-repeat
        center;
      background-size: 120% 120%;
    }
    .BoxTitle-title-title {
      color: #fff;
      text-shadow: 2px 2px 2px #50729c;
      margin-left: 5px;
      font-size: 14px;
      font-weight: 600;
      width: 60px;
      white-space: nowrap;
    }
  }
  .danwei {
    position: absolute;
    color: #fff;
    left: 80%;
    top: 5%;
    font-size: 10px;
  }
}
</style>
